package org.melanesia.beans;

import java.util.List;

/**
 * Composite property getter. This class implements getting values for composite
 * properties as described in {@link Getter#get(Object)}.
 * 
 * @author marcin.kielar
 * 
 */
class CompositeGetter implements Getter {

    /**
     * The accessor chain, i.e. list of <code>PropertyAccessor</code>s, which,
     * invoked sequentially will eventually lead to accessing the composite
     * property value.
     */
    private final List<PropertyAccessor> propertyAccessorList;

    /**
     * Constructs the <code>CompositeGetter</code>.
     * 
     * @param propertyAccessorList
     *            accessor chain
     */
    CompositeGetter(final List<PropertyAccessor> propertyAccessorList) {
        this.propertyAccessorList = propertyAccessorList;
    }

    @Override
    public Object get(final Object bean) {

        Object currentBean = bean;
        Object result = null;

        for (int i = 0, size = propertyAccessorList.size(); i < size; i++) {

            PropertyAccessor accessor = propertyAccessorList.get(i);

            if (i + 1 == size) {

                // Last property in chain
                result = accessor.get(currentBean);

            } else {

                // Intermediate property
                Object subBean = accessor.get(currentBean);
                if (subBean == null) {
                    return null;
                }

                currentBean = subBean;
            }
        }

        return result;
    }

    @Override
    public Class<?> getReturnType() {
        return propertyAccessorList.get(propertyAccessorList.size() - 1).getPropertyClass();
    }

}
